package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IRegionService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService{

    @Autowired
    private RegionRepository regionRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public Region get(String id) {
        return regionRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionRepository.findAll();
    }

    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        //条件
        Query query = new Query();
        //获取query
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(mongoTemplate,Region.class,pageable,query);
    }

    @Override
    public void saveOrUpdate(Region region) {
        //保存和更新,
        //更新是全量的,需要先查,后替换,然后更新
        //判断是否有id
        if(StringUtils.hasLength(region.getId())){
            this.update(region);
        }else{
            this.save(region);
        }
    }

    @Override
    public List<Destination> getDestByRegionId(String rid) {
        //获取对应区域
        if(StringUtils.hasLength(rid)){
            //获取地域
            Region region = this.get(rid);
            //获取地域相关的儿子
            List<String> ids = region.getRefIds();
            //通过数组获取目的地
            List<Destination> destinations = destinationService.findByIdIn(ids);
            return destinations;
        }
        return null;
    }

    @Override
    public void changeHotValue(String id, int hot) {
        Region region = this.get(id);
        region.setIshot(hot);
        this.update(region);
    }

    @Override
    public List<Region> queryHotRegion() {
        //获取热门并且按照sequence排序
        return regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
    }
}

